<?php
namespace llkphp\workerman\process\http;

use think\App;
use think\Http;
use think\helper\Str;
use think\response\View;
use think\exception\Handle;

use llkphp\workerman\process\http\think\App as WorkerApp;
use llkphp\workerman\process\http\think\Http as WorkerHttp;
use llkphp\workerman\process\http\think\Sandbox;
use llkphp\workerman\process\http\concerns\ModifyProperty;
use llkphp\workerman\process\http\think\response\File as FileResponse;
use llkphp\workerman\process\http\think\response\Iterator as IteratorResponse;

use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request as WorkerRequest;
use Workerman\Protocols\Http\Response;
use Workerman\Protocols\Http\Chunk;
use Workerman\Timer;

use Closure;
use Throwable;

class Handler
{
    use ModifyProperty;

    /**
     * @var WorkerApp
     */
    protected $app;

    
    /**
     * @var App
     */
    protected $container;

    /**
     * Manager constructor.
     * @param App $container
     */
    public function __construct(App $container)
    {
        $this->container = $container;
    }

    public function onWorkerStart()
    {
         // 初始化application
         $this->prepareApplication();

         $this->preloadHttp();

         $this->heartbeat();
    }

    /**
     * 数据库心跳
     */
    public function heartbeat()
    {
        $db = $this->app->db;
		Timer::add(10, function() use($db) {
			$intances = $db->getInstance();
			if (count($intances) <= 0) {
				return;
			}

			foreach($intances as $connection) {
				try {
					$connection->query('select 1');
				} catch (Throwable $e) {}
			}
		});
    }

    protected function preloadHttp()
    {
        $http = $this->app->http;
        $this->app->invokeMethod([$http, 'loadMiddleware'], [], true);

        if ($this->app->config->get('app.with_route', true)) {
            $this->app->invokeMethod([$http, 'loadRoutes'], [], true);
            $route = clone $this->app->route;
            unset($this->app->route);

            $this->app->resolving(WorkerHttp::class, function ($http, App $app) use ($route) {
                $newRoute = clone $route;
                $this->modifyProperty($newRoute, $app);
                $app->instance('route', $newRoute);
            });
        }

        $middleware = clone $this->app->middleware;
        unset($this->app->middleware);

        $this->app->resolving(WorkerHttp::class, function ($http, App $app) use ($middleware) {
            $newMiddleware = clone $middleware;
            $this->modifyProperty($newMiddleware, $app);
            $app->instance('middleware', $newMiddleware);
        });

        unset($this->app->http);
        $this->app->bind(Http::class, WorkerHttp::class);
    }

    protected function prepareApplication()
    {
        if (!$this->app instanceof WorkerApp) {
            $this->app = new WorkerApp($this->container->getRootPath());

            $this->app->bind(WorkerApp::class, App::class);
            $this->app->bind(Handler::class, $this);

            $this->app->initialize();
            $this->app->instance('request', $this->container->request);
            $this->prepareConcretes();
        }
    }

    /**
     * 预加载
     */
    protected function prepareConcretes()
    {
        $defaultConcretes = ['db', 'cache', 'event'];

        $concretes = array_merge($defaultConcretes, []);

        foreach ($concretes as $concrete) {
            $this->app->make($concrete);
        }
    }

    public function onMessage(TcpConnection $connection, WorkerRequest $request): void
    {
        $this->runInSandbox(function (Http $http, WorkerApp $app) use ($connection, $request) {

            $app->setInConsole(false);

            $request = $this->prepareRequest($request);

            try {
                $response = $this->handleRequest($http, $request);
                $this->prepareResponse($response);
            } catch (Throwable $e) {
                $handle = $app->make(Handle::class);
                $handle->report($e);
                $response = $handle->render($request, $e);
            }

            $this->sendResponse($connection, $request, $response, $app->cookie);

            //关闭连接
            $connection->close();

            $http->end($response);
        });
    }

    protected function sendResponse(TcpConnection $connection, \think\Request $request, \think\Response $response, \think\Cookie $cookie)
    {
        switch (true) {
            case $response instanceof IteratorResponse:
                $this->sendIterator($connection, $response, $cookie);
                break;
            case $response instanceof FileResponse:
                $this->sendFile($connection, $request, $response, $cookie);
                break;
            default:
                $this->sendContent($connection, $response, $cookie);
        }
    }

    protected function sendContent(TcpConnection $connection, \think\Response $response, \think\Cookie $cookie)
    {
        $response->header(['Transfer-Encoding' => 'chunked']);

        $wkResponse = $this->createResponse($response, $cookie);

        $connection->send($wkResponse);

        $content = $response->getContent();
        if ($content) {
            $contentSize = strlen($content);
            $chunkSize   = 8192;

            if ($contentSize > $chunkSize) {
                $sendSize = 0;
                do {
                    if (!$connection->send(new Chunk(substr($content, $sendSize, $chunkSize)))) {
                        break;
                    }
                } while (($sendSize += $chunkSize) < $contentSize);
            } else {
                $connection->send(new Chunk($content));
            }
        }
        $connection->send(new Chunk(''));
    }

    protected function sendFile(TcpConnection $connection, \think\Request $request, FileResponse $response, \think\Cookie $cookie)
    {
        $ifNoneMatch = $request->header('If-None-Match');
        $ifRange     = $request->header('If-Range');

        $code         = $response->getCode();
        $file         = $response->getFile();
        $eTag         = $response->getHeader('ETag');
        $lastModified = $response->getHeader('Last-Modified');

        $fileSize = $file->getSize();
        $offset   = 0;
        $length   = -1;

        if ($ifNoneMatch == $eTag) {
            $code = 304;
        } elseif (!$ifRange || $ifRange === $eTag || $ifRange === $lastModified) {
            $range = $request->header('Range', '');
            if (Str::startsWith($range, 'bytes=')) {
                [$start, $end] = explode('-', substr($range, 6), 2) + [0];

                $end = ('' === $end) ? $fileSize - 1 : (int) $end;

                if ('' === $start) {
                    $start = $fileSize - $end;
                    $end   = $fileSize - 1;
                } else {
                    $start = (int) $start;
                }

                if ($start <= $end) {
                    $end = min($end, $fileSize - 1);
                    if ($start < 0 || $start > $end) {
                        $code = 416;
                        $response->header([
                            'Content-Range' => sprintf('bytes */%s', $fileSize),
                        ]);
                    } elseif ($end - $start < $fileSize - 1) {
                        $length = $end < $fileSize ? $end - $start + 1 : -1;
                        $offset = $start;
                        $code   = 206;
                        $response->header([
                            'Content-Range'  => sprintf('bytes %s-%s/%s', $start, $end, $fileSize),
                            'Content-Length' => $end - $start + 1,
                        ]);
                    }
                }
            }
        }

        $wkResponse = $this->createResponse($response, $cookie);

        if ($code >= 200 && $code < 300 && $length !== 0) {
            $wkResponse->withFile($file->getPathname(), $offset, $length);
        }

        $connection->send($wkResponse);
    }

    protected function sendIterator(TcpConnection $connection, IteratorResponse $response, \think\Cookie $cookie)
    {
        $wkResponse = $this->createResponse($response, $cookie);
        $connection->send($wkResponse);

        foreach ($response as $content) {
            $connection->send($content, true);
        }
    }

    protected function createResponse(\think\Response $response, \think\Cookie $cookie, $body = '')
    {
        $code   = $response->getCode();
        $header = $response->getHeader();

        $wkResponse = new Response($code, $header, $body);

        foreach ($cookie->getCookie() as $name => $val) {
            [$value, $expire, $option] = $val;
            $wkResponse->cookie($name, $value, $expire, $option['path'], $option['domain'], (bool) $option['secure'], (bool) $option['httponly'], $option['samesite']);
        }

        return $wkResponse;
    }

    protected function prepareResponse(\think\Response $response)
    {
        switch (true) {
            case $response instanceof View:
                $response->getContent();
                break;
        }
    }

    protected function handleRequest(Http $http, $request)
    {
        $level = ob_get_level();
        ob_start();

        $response = $http->run($request);

        if (ob_get_length() > 0) {
            $content = $response->getContent();
            $response->content(ob_get_contents() . $content);
        }

        while (ob_get_level() > $level) {
            ob_end_clean();
        }

        return $response;
    }

    protected function prepareRequest(WorkerRequest $wkRequest)
    {
        $header = $wkRequest->header();
        $server = [];

        foreach ($header as $key => $value) {
            $server['http_' . str_replace('-', '_', $key)] = $value;
        }

        // 重新实例化请求对象 处理请求数据
        /** @var \think\Request $request */
        $request = $this->app->make('request', [], true);;

        $queryString = $wkRequest->queryString();

        return $request
            ->setMethod($wkRequest->method())
            ->withHeader($header)
            ->withServer($server)
            ->withGet($wkRequest->get())
            ->withPost($wkRequest->post())
            ->withCookie($wkRequest->cookie())
            ->withFiles($wkRequest->file())
            ->withInput($wkRequest->rawBody())
            ->setBaseUrl($wkRequest->uri())
            ->setUrl($wkRequest->uri() . (!empty($queryString) ? '?' . $queryString : ''))
            ->setPathinfo(ltrim($wkRequest->path(), '/'));
    }

    /**
     * 在沙箱中执行
     * @param Closure $callable
     */
    public function runInSandbox(Closure $callable, ?object $key = null)
    {
        try {
            $this->getSandbox()->run($callable, $key);
        } catch (Throwable $e) {
            $this->logServerError($e);
        }
    }

    /**
     * 获取沙箱
     * @return Sandbox
     */
    protected function getSandbox()
    {
        return $this->app->make(Sandbox::class);
    }

    /**
     * Log server error.
     *
     * @param Throwable $e
     */
    public function logServerError(Throwable $e)
    {
        /** @var Handle $handle */
        $handle = $this->container->make(Handle::class);

        $handle->report($e);
    }
}